/**
 * 历史记录管理工具
 */

export interface HistoryRecord {
  type: 'editor' | 'page'
  proType?: string
  newData?: any
  oldData?: any
  timestamp: number
}

export interface HistoryRecords {
  done: HistoryRecord[]
  undone: HistoryRecord[]
  isUndoRedo: boolean
}

/**
 * 添加历史记录
 */
export function addHistory(
  historyRecords: HistoryRecords,
  type: 'editor' | 'page',
  data: {
    proType?: string
    newData?: any
    oldData?: any
  }
) {
  if (historyRecords.isUndoRedo) {
    return
  }

  const record: HistoryRecord = {
    type,
    proType: data.proType,
    newData: data.newData,
    oldData: data.oldData,
    timestamp: Date.now()
  }

  historyRecords.done.push(record)
  historyRecords.undone = [] // 清空重做记录
}

/**
 * 撤销操作
 */
export function undoHistoryRecord(
  historyRecords: HistoryRecords,
  callback: (record: HistoryRecord) => void
) {
  if (historyRecords.done.length === 0) {
    return
  }

  historyRecords.isUndoRedo = true
  const record = historyRecords.done.pop()!
  historyRecords.undone.push(record)
  callback(record)
  historyRecords.isUndoRedo = false
}

/**
 * 重做操作
 */
export function redoHistoryRecord(
  historyRecords: HistoryRecords,
  callback: (record: HistoryRecord) => void
) {
  if (historyRecords.undone.length === 0) {
    return
  }

  historyRecords.isUndoRedo = true
  const record = historyRecords.undone.pop()!
  historyRecords.done.push(record)
  callback(record)
  historyRecords.isUndoRedo = false
}

/**
 * 清空历史记录
 */
export function clearHistory(historyRecords: HistoryRecords) {
  historyRecords.done = []
  historyRecords.undone = []
  historyRecords.isUndoRedo = false
}
